import entity.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.*;

/**
 * Createdbyv-chennanxinon2015/7/9.
 */
public class JSONTest {
    public JSONObject obj  = new JSONObject();
    public JSONObject obj2 = new JSONObject();
    /**
     * 有嵌套的json，{"second":{"name":"b","id":"2"},"first":{"name":"a","id":"1"}}
     */
    public JSONObject obj3 = new JSONObject();

    //自己生成键值对
    {
        obj.put("name", "a");
        obj.put("id", "1");
    }

    /**
     * JSONArray 类型，[{"name":"a","id":"1"},{"name":"b","id":"2"}]
     */
    public JSONArray array = new JSONArray();

    //List 转josnArray
    {
        List List = new ArrayList();
        obj2.put("name", "b");
        obj2.put("id", "2");
        List.add(obj);
        List.add(obj2);
        array.addAll(List);
        System.out.println("in class init: jsonArray.toString()" + array.toString());
    }

    //Map 转json
    {
        //一层Map
        Map map = new HashMap<>();
        map.put("name", "c");
        map.put("id", "3");
        obj3 = JSONObject.fromObject(map);
        System.out.println("in class init,一层map,obj3:" + obj3);
        //嵌套Map
        Map<String , JSONObject> map2 = new HashMap<>();
        map2.put("first", obj);
        map2.put("second", obj2);

        obj3 = JSONObject.fromObject(map2);
        System.out.println("in class init,二层map,obj3:" + obj3.toString ());
    }


    public static void main(String [] args) {
        JSONTest test = new JSONTest();

        //json转String 在init中就有

        //josn转List ，[{"name":"a","id":"1"},{"name":"b","id":"2"}]
//        List<User> List = new ArrayList<>();
        System.out.println("test.array:"+test.array);
        Collection<User> collection = JSONArray.toCollection(test.array, User.class);
        List<User> list = new ArrayList<>(collection);

        //josn转Map 
        Map<String , User> map = new HashMap<>();
        for (Object key : test.obj3.keySet()) {
            Object v = test.obj3.get(key);
            if(v instanceof JSONObject){
//                List list = new ArrayList()
            }
        }
    }

}